package com.ruoyi.mes.controller;

import com.ruoyi.mes.controller.DevicesController;
import com.ruoyi.mes.domain.DeviceControlCommand;
import com.ruoyi.mes.domain.DeviceStatus;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;

import java.util.List;

@Controller
public class DeviceWebSocketController {

    private final SimpMessagingTemplate messagingTemplate;
    private final MqttClientController mqttClientController;

    // 定义最大等待时间（例如：5秒）
    private static final long MAX_WAIT_TIME_MS = 15000;
    // 定义每次轮询的间隔时间（例如：200毫秒）
    private static final long POLL_INTERVAL_MS = 1000;

    @Autowired
    public DeviceWebSocketController(SimpMessagingTemplate messagingTemplate,
                                     MqttClientController mqttClientController) {
        this.messagingTemplate = messagingTemplate;
        this.mqttClientController = mqttClientController;
    }

    /**
     * 接收设备控制命令
     */
    @MessageMapping("/device/control")
    public void controlDevice(DeviceControlCommand command) throws MqttException {
//        DeviceStatus status =  devicesController.controller(command.getDevice(), command.getCommand());

        mqttClientController.Publish(command.getDevice(), command.getCommand());
        mqttClientController.Subscribe(command.getDevice());
        DeviceStatus deviceStatus = null;

        long startTime = System.currentTimeMillis();

        while (System.currentTimeMillis() - startTime < MAX_WAIT_TIME_MS) {
            deviceStatus = mqttClientController.getDeviceStatus(command.getDevice());
            if (deviceStatus != null && "finish".equals(deviceStatus.getStatus())) {
                System.out.println("成功获取到 'finish' 状态: " + deviceStatus);
                break; // 状态为 "finish"，跳出循环
            } else {
                System.out.println("循环中：当前状态不是 'finish' 或为 null: " + deviceStatus + ", 继续等待...");
                try {
                    Thread.sleep(POLL_INTERVAL_MS); // 等待一小段时间再重试，避免CPU空转
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt(); // 重新设置中断标志
                    System.err.println("等待设备状态时线程被中断。");
                    break; // 被中断，跳出循环
                }
            }
        }
        if (deviceStatus != null && "finish".equals(deviceStatus.getStatus())) {
            System.out.println("最终返回给前端的值: " + deviceStatus);
            messagingTemplate.convertAndSend("/topic/device/status", deviceStatus);
        } else {
            // 超时或最终状态不符合要求
            System.err.println("错误：在规定时间内未获取到设备的 'finish' 状态。当前最终状态: " + deviceStatus);
            // 可以考虑发送一个错误或超时通知给前端
            // 例如：
            // messagingTemplate.convertAndSend("/topic/status", new DeviceStatus(command.getDevice(), "timeout"));

        }
    }




}








// 调用设备控制器处理设备控制命令
//        DeviceStatus status = null;
//        switch (command.getDevice()) {
//            case "sixArm":
//                status = devicesController.sixArm(command.getDevice(), command.getCommand());
//                break;
//            case "fourArm":
//                status = devicesController.fourArm(command.getDevice(), command.getCommand());
//                break;
//            case "inspection":
//                status = devicesController.inspection(command.getDevice(), command.getCommand());
//                break;
//            case "marking":
//                status = devicesController.marking(command.getDevice(), command.getCommand());
//                break;
//            case "threeArm":
//                status = devicesController.threeArm(command.getDevice(), command.getCommand());
//                break;
//            default:
//                status = new DeviceStatus();
//                status.setDevice(command.getDevice());
//                status.setStatus(404);
//        }